// Leon Yu's Utility Extensions (YUX)
// Cookie Utility
// This utility contains fairly intuitive cookie functions.


// Define yux object if it is not already defined
if (typeof yux === 'undefined') var yux = {};

yux.cookies = 
{
	// Encode the string using either 'encodeURIComponent' or 'escape'
	// If none of the encode function is supported, it simply returns the same string
	// 'escape/unescape' is supported in IE4 and N4, so if the browser doesn't support 'escape/unescape', it probably barely support JavaScript.
	encode : function (value)
	{
		if (window.encodeURIComponent)
			return encodeURIComponent(value);
		else if (window.escape)
			return escape(value);
		else
			return value.toString();
	},

	// Decode a string encoded using the above function.
	decode : function (value)
	{
		if (window.decodeURIComponent)
			return decodeURIComponent(value);
		else if (window.unescape)
			return unescape(value);
		else
			return value;
	},

	// Set a cookie
	// Only the first two parameters are required
	set : function (name, content, days_expires, path, domain)
	{
		if (name == null || name === '') return;
		if (content == null) var content = '';

		var CookieString = yux.cookies.encode(name) + '=' + yux.cookies.encode(content);

		if (days_expires)
		{
			var expiration = new Date();
			expiration.setTime(expiration.getTime() + (days_expires * 86400000));
			CookieString += '; expires=' + expiration.toUTCString();
		}
		if (path) CookieString += '; path=' + path;
		if (domain) CookieString += '; domain=' + domain;

		document.cookie = CookieString;
	},

	// Get a single cookie content by name
	// Return a string of the content
	get : function (name)
	{
		var pairs;
		var cookies = document.cookie.split('; ');
		for (var i = 0, len = cookies.length; i < len; i++)
		{
			pairs = cookies[i].split('=');
			if (yux.cookies.decode(pairs[0]) === name && pairs[1])
				return yux.cookies.decode(pairs[1]);
		}
		return null;
	},

	// Grab all the cookies return it in an array of objects
	/* format : [ { name : __NAME__ ; content : __CONTENT__ },
	              { name : __NAME__ ; content : __CONTENT__ },
	              { name : __NAME__ ; content : __CONTENT__ } ] */
	getAll : function ()
	{
		var cookies = document.cookie.split('; ');
		var CookieArray = [];

		for (var i = 0, len = cookies.length; i < len; i++)
		{
			var split = cookies[i].split('=', 2);
			if (split)
				CookieArray.push( { name : yux.cookies.decode(split[0]), content : yux.cookies.decode(split[1]) } );
		}
		return CookieArray;
	},

	// Delete a cookie by setting the expiration
	del : function (name)
	{
		yux.cookies.set(name, '', -30);
	}
}